<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
  record?: any;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success', items: any[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const selectedTemplate = ref('');
const medicineSearch = ref('');
const medicineCategory = ref('');
const usageInstructions = ref('');

// 处方项目
const prescriptionItems = ref<any[]>([]);

// 药品数据
const medicines = ref([
  {
    id: 'M001',
    name: '阿莫西林胶囊',
    specification: '0.25g*24粒',
    price: 15.5,
    stock: 100,
    category: 'antibiotic',
    unit: '粒',
  },
  {
    id: 'M002',
    name: '布洛芬片',
    specification: '0.1g*20片',
    price: 8.5,
    stock: 50,
    category: 'painkiller',
    unit: '片',
  },
  {
    id: 'M003',
    name: '维生素C片',
    specification: '0.1g*100片',
    price: 12,
    stock: 200,
    category: 'vitamin',
    unit: '片',
  },
  {
    id: 'M004',
    name: '头孢克肟胶囊',
    specification: '0.1g*12粒',
    price: 25,
    stock: 80,
    category: 'antibiotic',
    unit: '粒',
  },
  {
    id: 'M005',
    name: '地塞米松片',
    specification: '0.75mg*100片',
    price: 18,
    stock: 60,
    category: 'anti-inflammatory',
    unit: '片',
  },
]);

// 表格列定义
const prescriptionColumns = [
  {
    title: '药品名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 120,
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price',
    width: 80,
  },
  {
    title: '用量',
    key: 'dosage',
    width: 120,
  },
  {
    title: '频次',
    key: 'frequency',
    width: 120,
  },
  {
    title: '天数',
    key: 'duration',
    width: 100,
  },
  {
    title: '数量',
    key: 'quantity',
    width: 80,
  },
  {
    title: '小计',
    key: 'totalPrice',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
  },
];

// 计算属性
const filteredMedicines = computed(() => {
  let result = medicines.value;

  if (medicineCategory.value) {
    result = result.filter(
      (medicine) => medicine.category === medicineCategory.value,
    );
  }

  if (medicineSearch.value) {
    const search = medicineSearch.value.toLowerCase();
    result = result.filter(
      (medicine) =>
        medicine.name.toLowerCase().includes(search) ||
        medicine.specification.toLowerCase().includes(search),
    );
  }

  return result;
});

const prescriptionTotal = computed(() => {
  return prescriptionItems.value.reduce(
    (total, item) => total + item.totalPrice,
    0,
  );
});

// 方法
const onTemplateChange = (templateId: string) => {
  // 根据模板加载预设药品
  if (templateId === 'template1') {
    // 感冒发热模板
    prescriptionItems.value = [
      {
        id: 'M001',
        name: '阿莫西林胶囊',
        specification: '0.25g*24粒',
        price: 15.5,
        dosage: 1,
        frequency: 'bid',
        duration: 7,
        quantity: 14,
        totalPrice: 217,
        unit: '粒',
      },
    ];
  } else if (templateId === 'template2') {
    // 肠胃炎模板
    prescriptionItems.value = [
      {
        id: 'M004',
        name: '头孢克肟胶囊',
        specification: '0.1g*12粒',
        price: 25,
        dosage: 1,
        frequency: 'bid',
        duration: 5,
        quantity: 10,
        totalPrice: 250,
        unit: '粒',
      },
    ];
  }
};

const onCategoryChange = () => {
  // 分类变化处理
};

const searchMedicine = () => {
  // 搜索逻辑已在计算属性中实现
};

const addMedicine = (medicine: any) => {
  // 检查是否已存在
  const existingIndex = prescriptionItems.value.findIndex(
    (item) => item.id === medicine.id,
  );
  if (existingIndex !== -1) {
    message.warning('该药品已在处方中');
    return;
  }

  // 添加新药品
  const newItem = {
    ...medicine,
    dosage: 1,
    frequency: 'bid',
    duration: 7,
    quantity: 14,
    totalPrice: medicine.price * 14,
  };

  prescriptionItems.value.push(newItem);
  message.success('药品添加成功');
};

const calculateTotal = (index: number) => {
  const item = prescriptionItems.value[index];
  if (item) {
    // 智能计算数量：用量 × 频次 × 天数
    const frequencyMap = { qd: 1, bid: 2, tid: 3, qid: 4 };
    const dailyDosage =
      item.dosage * frequencyMap[item.frequency as keyof typeof frequencyMap];
    item.quantity = Math.ceil(dailyDosage * item.duration);
    item.totalPrice = item.price * item.quantity;
  }
};

const removeMedicine = (index: number) => {
  prescriptionItems.value.splice(index, 1);
};

const handleOk = () => {
  if (prescriptionItems.value.length === 0) {
    message.warning('请至少添加一种药品');
    return;
  }

  if (!usageInstructions.value.trim()) {
    message.warning('请填写用法说明');
    return;
  }

  message.success('处方添加成功');
  emit('success', prescriptionItems.value);
  emit('update:visible', false);

  // 重置数据
  resetForm();
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  selectedTemplate.value = '';
  medicineSearch.value = '';
  medicineCategory.value = '';
  usageInstructions.value = '';
  prescriptionItems.value = [];
};

// 监听模态框关闭
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      resetForm();
    }
  },
);
</script>

<template>
  <a-modal
    :open="visible"
    title="添加处方"
    width="900px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="prescription-modal">
      <!-- 处方模板选择 -->
      <div class="template-section">
        <h4>智能模板</h4>
        <a-select
          v-model:value="selectedTemplate"
          placeholder="选择处方模板"
          style="width: 300px"
          @change="onTemplateChange"
        >
          <a-select-option value="template1">感冒发热处方模板</a-select-option>
          <a-select-option value="template2">肠胃炎处方模板</a-select-option>
          <a-select-option value="template3">皮肤病处方模板</a-select-option>
          <a-select-option value="template4">外伤处理处方模板</a-select-option>
        </a-select>
      </div>

      <!-- 药品选择 -->
      <div class="medicine-section">
        <h4>药品选择</h4>
        <div class="search-row">
          <a-input
            v-model:value="medicineSearch"
            placeholder="搜索药品名称"
            style="width: 300px"
            @keyup.enter="searchMedicine"
          >
            <template #suffix>
              <a-button type="text" @click="searchMedicine">🔍</a-button>
            </template>
          </a-input>
          <a-select
            v-model:value="medicineCategory"
            placeholder="药品分类"
            style="width: 200px"
            @change="onCategoryChange"
          >
            <a-select-option value="antibiotic">抗生素</a-select-option>
            <a-select-option value="anti-inflammatory">消炎药</a-select-option>
            <a-select-option value="vitamin">维生素</a-select-option>
            <a-select-option value="painkiller">止痛药</a-select-option>
          </a-select>
        </div>

        <div class="medicine-grid">
          <div
            v-for="medicine in filteredMedicines"
            :key="medicine.id"
            class="medicine-card"
            @click="addMedicine(medicine)"
          >
            <div class="medicine-name">{{ medicine.name }}</div>
            <div class="medicine-spec">{{ medicine.specification }}</div>
            <div class="medicine-price">¥{{ medicine.price.toFixed(2) }}</div>
            <div class="medicine-stock">库存: {{ medicine.stock }}</div>
          </div>
        </div>
      </div>

      <!-- 处方详情 -->
      <div class="prescription-details">
        <h4>处方详情</h4>
        <a-table
          :columns="prescriptionColumns"
          :data-source="prescriptionItems"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'dosage'">
              <a-input-number
                v-model:value="record.dosage"
                :min="0.1"
                :max="100"
                :precision="1"
                style="width: 80px"
                @change="calculateTotal(index)"
              />
              <span style="margin-left: 4px">{{ record.unit }}</span>
            </template>
            <template v-else-if="column.key === 'frequency'">
              <a-select
                v-model:value="record.frequency"
                style="width: 100px"
                @change="calculateTotal(index)"
              >
                <a-select-option value="qd">每日1次</a-select-option>
                <a-select-option value="bid">每日2次</a-select-option>
                <a-select-option value="tid">每日3次</a-select-option>
                <a-select-option value="qid">每日4次</a-select-option>
              </a-select>
            </template>
            <template v-else-if="column.key === 'duration'">
              <a-input-number
                v-model:value="record.duration"
                :min="1"
                :max="30"
                style="width: 60px"
                @change="calculateTotal(index)"
              />
              <span style="margin-left: 4px">天</span>
            </template>
            <template v-else-if="column.key === 'quantity'">
              <a-input-number
                v-model:value="record.quantity"
                :min="1"
                :max="1000"
                style="width: 80px"
                @change="calculateTotal(index)"
              />
            </template>
            <template v-else-if="column.key === 'totalPrice'">
              ¥{{ record.totalPrice.toFixed(2) }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button
                type="text"
                danger
                size="small"
                @click="removeMedicine(index)"
              >
                删除
              </a-button>
            </template>
          </template>
        </a-table>

        <div class="total-section">
          <span class="total-label">处方总计:</span>
          <span class="total-amount">¥{{ prescriptionTotal.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 用法说明 -->
      <div class="usage-section">
        <h4>用法说明</h4>
        <a-textarea
          v-model:value="usageInstructions"
          placeholder="请输入详细的用法用量说明..."
          :rows="3"
        />
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.prescription-modal {
  max-height: 700px;
  overflow-y: auto;
}

.template-section {
  margin-bottom: 24px;
}

.template-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.medicine-section {
  margin-bottom: 24px;
}

.medicine-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.search-row {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.medicine-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.medicine-card {
  padding: 12px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  transition: all 0.3s;
}

.medicine-card:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.medicine-name {
  margin-bottom: 4px;
  font-weight: 600;
  color: #262626;
}

.medicine-spec {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.medicine-price {
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #f5222d;
}

.medicine-stock {
  font-size: 12px;
  color: #52c41a;
}

.prescription-details {
  margin-bottom: 24px;
}

.prescription-details h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.total-section {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-end;
  padding-top: 12px;
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.total-label {
  font-size: 14px;
  color: #666;
}

.total-amount {
  font-size: 18px;
  font-weight: 700;
  color: #f5222d;
}

.usage-section {
  margin-bottom: 16px;
}

.usage-section h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}
</style>
